package com.shouer.doc.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.shouer.doc.R;
import com.shouer.doc.application.App;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.common.util.SPUtils;
import com.shouer.doc.dialog.ShouerLoadingDialogUtil;
import com.shouer.doc.event.WXLoginCodeEvent;
import com.shouer.doc.ui.ShouerWebActivity;
import com.shouer.doc.ui.bindwechat.BindWeChatActivity;
import com.shouer.doc.ui.forgetpassword.ForgetPasswordActivity;
import com.shouer.doc.ui.login.presenter.ILoginPresenter;
import com.shouer.doc.ui.login.presenter.LoginPresenterCompl;
import com.shouer.doc.ui.login.response.WeChatLoginResponse;
import com.shouer.doc.ui.login.view.ILoginView;
import com.shouer.doc.ui.main.MainActivity;
import com.shouer.doc.widget.VipSelectBox;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnFocusChange;
import butterknife.OnTextChanged;

/**
 * Created by ZXL on 2016/11/25.
 */

public class LoginActivity extends AppCompatActivity implements ILoginView {

    private App app;
    private ILoginPresenter mLoginPresenter;

    private String userPhone, password;

    @BindView(R.id.name_input)
    protected EditText nameInput;
    @BindView(R.id.pass_input)
    protected EditText passInput;
    @BindView(R.id.name_del)
    protected View nameDel;
    @BindView(R.id.pass_del)
    protected View passDel;
    @BindView(R.id.login_btn)
    protected View loginBtn;
    @BindView(R.id.wx_login)
    protected View weChatLoginBtn;

    @BindView(R.id.check_btn)
    protected VipSelectBox selectBox;

    public static IWXAPI wxApi;
    private WeChatLoginResponse weChatLoginResponse;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_login_activity);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        app = (App) getApplicationContext();
        mLoginPresenter = new LoginPresenterCompl(this);
        initViews();
    }

    private void initViews() {
        userPhone = (String) SPUtils.get(this, "user_phone", "");
        password = (String) SPUtils.get(this, "user_pass", "");
        nameInput.setText(userPhone);
        passInput.setText(password);
        Integer isReadXy = (Integer) SPUtils.get(LoginActivity.this, "xieyi", 0);
        if (isReadXy==1)
        {
            selectBox.setChecked(true);
        }else
        {
            selectBox.setChecked(false);
        }

        if (selectBox.getChecked())
        {
            loginBtn.setBackgroundResource(R.drawable.blue_btn_bg);
        }else
        {
            loginBtn.setBackgroundResource(R.drawable.login_unable_bg);
        }
    }

    @Override
    public void onDestroy() {
        mLoginPresenter.onDestroy();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @OnClick(value = {R.id.login_btn, R.id.back_btn, R.id.name_del, R.id.pass_del, R.id.forget_pass, R.id.wx_login,R.id.read_xieyi,R.id.check_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.login_btn:
                if (selectBox.getChecked())
                {
                    loginBtn.setClickable(false);
                    userPhone = nameInput.getText().toString().trim();
                    if (userPhone.length() < 11) {
                        loginBtn.setClickable(true);
                        Toast.makeText(LoginActivity.this, "用户名为11位手机号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    password = passInput.getText().toString().trim();
                    if (password.length() < 6) {
                        loginBtn.setClickable(true);
                        Toast.makeText(LoginActivity.this, "密码长度不能少于6位", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    ShouerLoadingDialogUtil.getInstance().show(this);
                    mLoginPresenter.doLogin(userPhone, password);
                }else
                {
                    Toast.makeText(LoginActivity.this,"登录前请阅读并勾选首儿健康汇线上协议",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.name_del:
                nameInput.setText("");
                passInput.setText("");
                break;
            case R.id.pass_del:
                passInput.setText("");
                break;
            case R.id.forget_pass:
                Intent forgetIntent = new Intent(this, ForgetPasswordActivity.class);
                startActivity(forgetIntent);
                break;
            case R.id.wx_login:
                ShouerLoadingDialogUtil.getInstance().show(this);
                if (null == wxApi) {
                    wxApi = WXAPIFactory.createWXAPI(LoginActivity.this, ShouerConst.WX_LOGIN_APPID, true);
                    wxApi.registerApp(ShouerConst.WX_LOGIN_APPID);
                }
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "com.shouer.doc";
                wxApi.sendReq(req);
                break;
            case R.id.read_xieyi:
                Intent xiyiIntent=new Intent(this, ShouerWebActivity.class);
//                xiyiIntent.putExtra("title","首儿健康汇线上协议书");
                xiyiIntent.putExtra("url","http://shouer-share.shouerhealth.cn/shared/shouer_docXSXY.html");
                startActivity(xiyiIntent);
                break;
            case R.id.check_btn:
                if (selectBox.getChecked()) {
                    loginBtn.setBackgroundResource(R.drawable.login_unable_bg);
                    selectBox.setChecked(false);
                } else {
                    loginBtn.setBackgroundResource(R.drawable.blue_btn_bg);
                    selectBox.setChecked(true);
                }
                break;
        }
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public App getApp() {
        return app;
    }

    @Override
    public void loginFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        enableLogin();
        Toast.makeText(LoginActivity.this, failInfo, Toast.LENGTH_SHORT).show();
    }

    /**
     * 微信登录失败
     */
    @Override
    public void wechatLoginFailed(String failInfo) {
        ShouerLoadingDialogUtil.getInstance().dismiss();
        enableLogin();
        Toast.makeText(LoginActivity.this, failInfo, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void wechatLoginSuccess(WeChatLoginResponse response) {
        this.weChatLoginResponse=response;
    }

    /**
     * 提示医生绑定手机号
     */
    @Override
    public void bindWeChat(String refreshToken, String accessToken) {
        enableLogin();
        Intent intent=new Intent(this, BindWeChatActivity.class);
        intent.putExtra("access_token",accessToken);
        intent.putExtra("refresh_token",refreshToken);
        startActivity(intent);
    }

    /**
     * 登录成功
     */
    @Override
    public void loginSuccess() {
        SPUtils.put(LoginActivity.this, "xieyi", 1);
        ShouerLoadingDialogUtil.getInstance().dismiss();
        if (null!=getApp().getManService())
        {
            getApp().getManService().getMANAnalytics().updateUserAccount(getApp().getUserModel().getUserPhone(), getApp().getUserDocId());
        }
        SPUtils.put(this, "user_phone", userPhone);
        SPUtils.put(this, "user_pass", password);
        Intent mainIntent = new Intent(this, MainActivity.class);
        startActivity(mainIntent);
        finish();
    }


    @OnFocusChange(value = {R.id.name_input, R.id.pass_input})
    public void onFocusChange(View view, boolean hasFocus) {
        switch (view.getId()) {
            case R.id.name_input:
                if (hasFocus && nameInput.getText().length() > 0) {
                    nameDel.setVisibility(View.VISIBLE);
                } else {
                    nameDel.setVisibility(View.GONE);
                }
                break;
            case R.id.pass_input:
                if (hasFocus && passInput.getText().length() > 0) {
                    passDel.setVisibility(View.VISIBLE);
                } else {
                    passDel.setVisibility(View.GONE);
                }
                break;

        }

    }

    @OnTextChanged(value = {R.id.name_input}, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void afterTextChanged1(Editable s) {
        if (nameInput.hasFocus()) {
            if (s.length() > 0) {
                nameDel.setVisibility(View.VISIBLE);
            } else {
                nameDel.setVisibility(View.GONE);
            }
        }
    }

    @OnTextChanged(value = {R.id.pass_input}, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void afterTextChanged2(Editable s) {
        if (passInput.hasFocus()) {
            if (s.length() > 0) {
                passDel.setVisibility(View.VISIBLE);
            } else {
                passDel.setVisibility(View.GONE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(WXLoginCodeEvent event) {

        if (!TextUtils.isEmpty(event.getCode())) {
            mLoginPresenter.wechatLogin(event.getCode(),null,null);
        } else {
            enableLogin();
            ShouerLoadingDialogUtil.getInstance().dismiss();
        }

    }


    private void enableLogin()
    {
        loginBtn.setClickable(true);
        weChatLoginBtn.setClickable(true);
    }

    private void disableLogin()
    {
        loginBtn.setClickable(false);
        weChatLoginBtn.setClickable(false);
    }
}
